//
//  NSData+Mango.m
//  Mango
//
//  Created by 胡超 on 2017/12/25.
//  Copyright © 2017年 胡超., ltd. All rights reserved.
//

#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>

#import "NSData+Mango.h"

@implementation NSData (Mango)

- (NSString *)md5Str {
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(self.bytes, (CC_LONG)self.length, result); // This is the md5 call
    NSString *md5Str = @"";
    for (int i=0; i<CC_MD5_DIGEST_LENGTH; i++) {
        md5Str = [md5Str stringByAppendingFormat:@"%02x",result[i]];
    }
    return md5Str.lowercaseString;
}

- (NSData *)des:(CCOperation)op options:(MGDESOptions)options key:(const void *)key iv:(const void *)iv {
    const void *dataIn = self.bytes;
    size_t dataInLength = self.length;
    
    size_t dataOutAvailable = 0;
    size_t dataOutMoved = 0;
    
    dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
    uint8_t *dataOut = (uint8_t *)malloc(dataOutAvailable * sizeof(uint8_t));
    memset((void *)dataOut, 0x0, dataOutAvailable);
    
    CCCrypt(op, kCCAlgorithmDES, options, key, kCCKeySizeDES, iv, dataIn, dataInLength, (void *)dataOut, dataOutAvailable, &dataOutMoved);
    
    NSData *data = [NSData dataWithBytes:dataOut length:dataOutMoved];
    free(dataOut);
    return data;
}

- (NSData *)desEncryptData:(MGDESOptions)options key:(const void *)key iv:(const void *)iv {
    return [self des:kCCEncrypt options:options key:key iv:iv];
}

- (NSData *)desDecryptData:(MGDESOptions)options key:(const void *)key iv:(const void *)iv {
    return [self des:kCCDecrypt options:options key:key iv:iv];
}

@end
